package grouplife::Controller::Topic;
use Moose;
use namespace::autoclean;
use Catalyst::Request::Upload;
use Catalyst::Log;
use grouplife::Model::CommentedItem::CommentedItemModel;
use grouplife::Model::Topic::TopicCreateModel;
use grouplife::Model::Topic::TopicSearchModel;
use grouplife::Model::Users::UsersSearchModel;
use grouplife::Model::Tuan::TuansSearchModel;
use Util::Token::Token;
use Time::Seconds;
use Time::Piece;

BEGIN {extends 'Catalyst::Controller'; }
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Users - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

sub index :Path :Args(0) {
        my ($self, $c) = @_;

	my $universities = $c->model('University::UniversityModel')->get_all_univs();
	my $universities1 = $c->model('University::UniversityModel')->get_all_offices();
	my $topic_with_images = $c->model('Topic::TopicSearchModel')->get_topics_with_img(9);
	my $top_ten_topics = $c->model('Topic::TopicSearchModel')->get_top_ten_topic_for_today(-1);
	my %top_ten_all;
	foreach my $university (@$universities) {
		$top_ten_all{$university->id} = $c->model('Topic::TopicSearchModel')->get_top_ten_topic_for_today($university->id);
	}
	foreach my $university (@$universities1) {
		$top_ten_all{$university->id} = $c->model('Topic::TopicSearchModel')->get_top_ten_topic_for_today($university->id);
	}
	my $jinghua_topics = $c->model('Topic::TopicSearchModel')->get_jinghua();
	my $guapai_topics = $c->model('Topic::TopicSearchModel')->get_certain_types(7, 10);
	my $gonggao_topics = $c->model('Topic::TopicSearchModel')->get_certain_types(1, 10);
	my $diaocha_topics = $c->model('Topic::TopicSearchModel')->get_certain_types(3, 10);
	my $host_uri = $c->config->{host_uri};
        $c->stash(title => '讨论区');
        $c->stash(css => 'discuss_main.css'),
	$c->stash(login_user => $c->session->{login_user});
        $c->stash(template => 'topic/discuss_main.tt2');
        $c->stash(topic_with_images => $topic_with_images);
	$c->stash(cats => [$c->model('TopicType::TopicTypeModel')->get_all_topic_types]);
	$c->stash(top_ten_topics => $top_ten_topics );
	$c->stash(universities => $universities );
	$c->stash(host_uri => $host_uri );
	$c->stash(jinghua_topics => $jinghua_topics );
	$c->stash(universities1 => $universities1 );
	$c->stash(top_ten_all => \%top_ten_all );
	$c->stash(guapai_topics => $guapai_topics );
	$c->stash(gonggao_topics => $gonggao_topics );
	$c->stash(diaocha_topics => $diaocha_topics );
}

sub fenqu :Path('fenqu') :Args(0) {
        my ($self, $c) = @_;

	my $univ_id = $c->request->params->{univ_id};
	my $cat_id = $c->request->params->{cat_id};
	my $university;
	if(!$univ_id or $univ_id == -1) 
	{
		$univ_id = -1;
		$university = '全部单位';
	}
	else
	{
		$university = $c->model('University::UniversityModel')->find($univ_id);
	}
	my $category;
	if(!$cat_id or $cat_id == -1) 
	{
		$cat_id = -1;
		$category = '全部分类';
	}
	else 
	{
		$category = $c->model('TopicType::TopicTypeModel')->find($cat_id);
	}
	my $users= $c->model('Topic::TopicSearchModel')->find_last_upd_user($c);
	my $universities = $c->model('University::UniversityModel')->get_all_univs();
	my $universities1 = $c->model('University::UniversityModel')->get_all_offices();
	$c->stash(users=> $users);
        $c->stash(title => '讨论区');
        $c->stash(css => 'discuss.css'),
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(javascript => '/topic/discuss.js');
        $c->stash(template => 'topic/discuss.tt2');
	$c->stash(cats => [$c->model('TopicType::TopicTypeModel')->get_all_topic_types]);
	$c->stash(universities => $universities );
	$c->stash(universities1 => $universities1 );
	$c->stash(cat_id => $cat_id);
	$c->stash(univ_id => $univ_id);
	$c->stash(category => $category);
	$c->stash(university => $university);
}

sub form_create_zhengyou :Chained('base') :PathPart('form_create_zhengyou') :Args(0) {
	my ($self, $c) = @_;
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = '/topic/form_create_zhengyou';
                return 0;
        }
        my $biaoti = $c->request->params->{biaoti};
        my $neirong = $c->request->params->{neirong};
        my $danwei_id = $c->request->params->{danwei_id};
        my $type_id = $c->request->params->{type_id};

	my $user_tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($c->session->{login_user}->id);
        my $user_renzheng_status = 'U'; #'U'表示未提交申请
        if (defined $user_tuanzhang_info) {
                $user_renzheng_status = $user_tuanzhang_info->status;
        }
	my $is_admin = $c->model('UserTuan::UserTuanModel')->is_admin($c->session->{login_user},$c->session->{login_user});
	#my @cats = $c->model('TopicType::TopicTypeModel')->get_all_topic_types();
	my $universities = $c->model('University::UniversityModel')->get_all();
	my $host_uri = $c->config->{host_uri};
	my $token = Util::Token::Token->new();
	$c->session->{token} = $token->generate_token();
	$c->stash(title => '发起新话题');
	$c->stash(is_zhengyou => 'Y');
	$c->stash(css => 'fabu.css');
	$c->stash(token => $c->session->{token});
	$c->stash(host_uri  => $host_uri);
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(javascript => '/topic/form_create.js');
	$c->stash(cats => [$c->model('TopicType::TopicTypeModel')->get_all_topic_types]);
	$c->stash(universities => $universities);
	$c->stash(template => 'topic/form_create.tt2');
	$c->stash(is_admin => $is_admin);
	$c->stash(user_renzheng_status => $user_renzheng_status);
	$c->stash(neirong => $neirong);
	$c->stash(biaoti => $biaoti);
	$c->stash(danwei_id => $danwei_id);
	$c->stash(type_id => $type_id);
	$c->stash(user => $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id));
	my $user = $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id);
	if(defined($user->university)) {
		$c->stash(userUniv => $user->university);
	}
	if(defined($user->office)) {
		$c->stash(userOffice => $user->office);
	}
	if(defined($user->house)) {
		$c->stash(userHouse => $user->house);
	}
}

sub form_create :Chained('base') :PathPart('form_create') :Args(0) {
	my ($self, $c) = @_;
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = '/topic/form_create';
                return 0;
        }
        my $biaoti = $c->request->params->{biaoti};
        my $neirong = $c->request->params->{neirong};
        my $danwei_id = $c->request->params->{danwei_id};
        my $type_id = $c->request->params->{type_id};

	my $user_tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($c->session->{login_user}->id);
        my $user_renzheng_status = 'U'; #'U'表示未提交申请
        if (defined $user_tuanzhang_info) {
                $user_renzheng_status = $user_tuanzhang_info->status;
        }
	my $is_admin = $c->model('UserTuan::UserTuanModel')->is_admin($c->session->{login_user},$c->session->{login_user});
	#my @cats = $c->model('TopicType::TopicTypeModel')->get_all_topic_types();
	my $universities = $c->model('University::UniversityModel')->get_all();
	my $host_uri = $c->config->{host_uri};
	my $token = Util::Token::Token->new();
	$c->session->{token} = $token->generate_token();
	$c->stash(title => '发起新话题');
	$c->stash(css => 'fabu.css');
	$c->stash(token => $c->session->{token});
	$c->stash(host_uri  => $host_uri);
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(javascript => '/topic/form_create.js');
	$c->stash(cats => [$c->model('TopicType::TopicTypeModel')->get_all_topic_types]);
	$c->stash(universities => $universities);
	$c->stash(template => 'topic/form_create.tt2');
	$c->stash(is_admin => $is_admin);
	$c->stash(user_renzheng_status => $user_renzheng_status);
	$c->stash(neirong => $neirong);
	$c->stash(biaoti => $biaoti);
	$c->stash(danwei_id => $danwei_id);
	$c->stash(type_id => $type_id);
	$c->stash(user => $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id));
	my $user = $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id);
	if(defined($user->university)) {
		$c->stash(userUniv => $user->university);
	}
	if(defined($user->office)) {
		$c->stash(userOffice => $user->office);
	}
	if(defined($user->house)) {
		$c->stash(userHouse => $user->house);
	}
}

sub topic_total:Local {
        my ($self, $c) = @_;

	my $univ_id = $c->request->params->{univ_id};
	my $cat_id = $c->request->params->{cat_id};
        $c->res->output($c->model('Topic::TopicSearchModel')->get_topic_count_by_univ_cat($univ_id, $cat_id));
}

sub topic_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};
	my $univ_id = $c->request->params->{univ_id};
	my $cat_id = $c->request->params->{cat_id};
        my $page = $start_index / 20;
        $page = $page + 1;

	my ($topics, $images) = $c->model('Topic::TopicSearchModel')->topic_search_by_univ_cat($page, $univ_id, $cat_id, 20);
	
        $c->stash(
                login_user => $c->session->{login_user},
                nowrapper => 1,
                template => 'topic/topic_search.tt2',
		images => $images,
		topics => $topics
        );
}

sub xiugai:Local {
        my ($self, $c) = @_;

        my $topic_id  = $c->request->params->{topic_id};

	my $topic = $c->model('Topic::TopicSearchModel')->find($topic_id);
	my $universities = $c->model('University::UniversityModel')->get_all();
	my $host_uri = $c->config->{host_uri};
	my $user_tuanzhang_info = $c->model('TuanZhang::TuanZhangModel')->tuanzhang_request_search($c->session->{login_user}->id);
        my $user_renzheng_status = 'U'; #'U'表示未提交申请
        if (defined $user_tuanzhang_info) {
                $user_renzheng_status = $user_tuanzhang_info->status;
        }
	my $is_admin = $c->model('UserTuan::UserTuanModel')->is_admin($c->session->{login_user},$c->session->{login_user});
	$c->stash(title => '修改话题');
	$c->stash(css => 'fabu.css'),
	$c->stash(host_uri  => $host_uri),
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(javascript => '/topic/form_create.js');
	$c->stash(cats => [$c->model('TopicType::TopicTypeModel')->get_all_topic_types]);
	$c->stash(topic => $topic);
	$c->stash(universities => $universities);
	$c->stash(template => 'topic/edit_topic.tt2');
	$c->stash(is_admin => $is_admin);
	$c->stash(user_renzheng_status => $user_renzheng_status);
	my $user = $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id);
	$c->stash(user => $user);
	if(defined($user->university)) {
		$c->stash(userUniv => $user->university);
	}
	if(defined($user->office)) {
		$c->stash(userOffice => $user->office);
	}
	if(defined($user->house)) {
		$c->stash(userHouse => $user->house);
	}
}

sub xiugai_do :Local {
        my ($self, $c) = @_;

        my $topic_id  = $c->request->params->{topic_id};
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = $c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic_id]);
                return 0;
        }
        my $biaoti = $c->request->params->{biaoti};
        my $neirong = $c->request->params->{neirong};
        my $type_id = $c->request->params->{topicCategory};
        my $danwei_id = $c->request->params->{topicUniversity};

	my @message;
	unless(defined $type_id) {
		push(@message, "你没有选择帖子种类");
	}
	unless(defined $danwei_id and $danwei_id ne "") {
		push(@message, "你没有选择发布单位");
	}
	unless(defined $biaoti and $biaoti ne "") {
		push(@message, "你没有输入帖子标题");
	}
	unless(defined $neirong and $neirong ne "") {
		push(@message, "你没有输入帖子内容");
	}

	if(scalar(@message) != 0) {
		$c->stash(login_user => $c->session->{login_user});
                $c->stash(messages => \@message);
		$c->stash(css   => 'zhuce.css');
                $c->stash(template => 'topic/topic_edit_failed.tt2');
		$c->stash(topic_id => $topic_id);
	}
	else {
        	my $topic = $c->model('Topic::TopicCreateModel')->update($topic_id, $biaoti, $neirong, $c->user->id, $type_id, $danwei_id);
		$c->response->redirect($c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic->id]));
	}
}

sub shanchu :Local {
        my ($self, $c) = @_;

        my $topic_id  = $c->request->params->{topic_id};
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = $c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic_id]);
                return 0;
        }
        my $topic = $c->model('Topic::TopicCreateModel')->expire_topic($topic_id);

        $c->response->redirect($c->uri_for('/topic'));
}

sub jinghua:Local {
        my ($self, $c) = @_;

        my $topic_id  = $c->request->params->{topic_id};
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = $c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic_id]);
                return 0;
        }
        my $current_id = $c->session->{login_user}->id; 
        my $topic = $c->model('Topic::TopicCreateModel')->change_jinghua($topic_id,'Y',$current_id);

	$c->response->redirect($c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic->id]));
}

sub chexiao_jinghua:Local {
        my ($self, $c) = @_;

        my $topic_id  = $c->request->params->{topic_id};
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = $c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic_id]);
                return 0;
        }
        my $topic = $c->model('Topic::TopicCreateModel')->change_jinghua($topic_id,'N',);

	$c->response->redirect($c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic->id]));
}

sub zhiding:Local {
        my ($self, $c) = @_;

        my $topic_id  = $c->request->params->{topic_id};
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = $c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic_id]);
                return 0;
        }
        my $current_id = $c->session->{login_user}->id; 
        my $topic = $c->model('Topic::TopicCreateModel')->change_zhiding($topic_id,'Y',$current_id);

	$c->response->redirect($c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic->id]));
}

sub cheding:Local {
        my ($self, $c) = @_;

        my $topic_id  = $c->request->params->{topic_id};
        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = $c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic_id]);
                return 0;
        }
        my $current_id = $c->session->{login_user}->id; 
        my $topic = $c->model('Topic::TopicCreateModel')->change_zhiding($topic_id,'N',$current_id);

	$c->response->redirect($c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic->id]));
}

sub fabu :Local {
        my ($self, $c) = @_;

        if (!$c->user_exists) {
                $c->response->redirect($c->uri_for('/login'));
                $c->flash->{redirect_after_login} = '/topic/form_create';
                return 0;
        }
        my $biaoti = $c->request->params->{biaoti};
        my $neirong = $c->request->params->{neirong};
        my $type_id = $c->request->params->{topicCategory};
        my $danwei_id = $c->request->params->{topicUniversity};
        my $get_token = $c->request->params->{token} || '';

        my $session_token = $c->session->{token};
        my $token = Util::Token::Token->new();
        $c->session->{token} = $token->generate_token();
        if($get_token eq $session_token) {
		my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('5');

		my @message;
		unless(defined $type_id) {
			push(@message, "你没有选择帖子种类");
		}
		unless(defined $danwei_id and $danwei_id ne "") {
			push(@message, "你没有选择发布单位");
		}
		unless(defined $biaoti and $biaoti ne "") {
			push(@message, "你没有输入帖子标题");
		}
		unless(defined $neirong and $neirong ne "") {
			push(@message, "你没有输入帖子内容");
		}

		if(scalar(@message) != 0) {
			$c->stash(login_user => $c->session->{login_user});
			$c->stash(messages => \@message);
			$c->stash(css   => 'zhuce.css');
			$c->stash(template => 'topic/topic_create_failed.tt2');
			$c->stash(neirong => $neirong);
			$c->stash(biaoti => $biaoti);
			$c->stash(danwei_id => $danwei_id);
			$c->stash(type_id => $type_id);
		}
		else {
			my $topic = $c->model('Topic::TopicCreateModel')->create($biaoti, $neirong, $commented_item->id, $c->user->id, $type_id, $danwei_id);
			$c->user->add_to_my_news({user_id=>$c->user->id, photo=>$c->user->photo, event_type_id=>8, me_name=>$c->user->username, target_id=>$topic->id, target_name=>$topic->title});
			$c->response->redirect($c->uri_for($c->controller('Topic')->action_for('topic_info'), [$topic->id]));
		}
	} else {
		$c->stash(css   => 'zhuce.css');
                $c->stash(login_user => $c->session->{login_user});
                $c->stash(template => 'resubmit/resubmit.tt2');
	}
}

sub topics {
        my ($self, $c) = @_;

        my @topics = $c->model('Topic::TopicSearchModel')->get_all();
	$c->stash(title => '讨论区');
	$c->stash(css => 'topic.css'),
	$c->stash(javascript => '/topic/topic_main.js');
	$c->stash(template => 'topic/topic_mainpage.tt2');
}

sub base :Chained('/') :PathPart('topic') :CaptureArgs(0) {
        my ($self, $c) = @_;
}

sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
        my ($self, $c, $id) = @_;
        $c->stash(object => $c->model('Topic::TopicSearchModel')->find($id));
        $c->stash(id => $id);
}

sub topic_info :Chained('object') :PathPart('topic_info') :Args(0) {
	my ($self, $c) = @_;

	$c->model('Topic::TopicCreateModel')->update_counter($c->stash->{object});
	my $login = 'N';
	if (defined $c->session->{login_user}) {
                $login = 'L';
               	my $current_id = $c->session->{login_user}->id; 
		my $is_admin = $c->model('UserTuan::UserTuanModel')->is_admin($c->session->{login_user},$c->session->{login_user});
		$c->stash(is_admin => $is_admin);
		my $is_creater = '0';
		if($current_id == $c->stash->{object}->author_id)
		{
			$is_creater = '1';
		}
		$c->stash(is_creater => $is_creater);
        }
	my @comments = $c->model('Comments::CommentsForTopicModel')->get_comments($c->stash->{object}->comm_item_id);
	my $university_id = $c->stash->{object}->university->id;
	my $topics = $c->model('Topic::TopicSearchModel')->get_topic_for_university($university_id, 50);
	$c->stash(comments => @comments) if(scalar(@comments) != 0);
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(title => $c->stash->{object}->title);
	$c->stash(topics => $topics);
	$c->stash(javascript => 'topic/topic_all.js',
		topic => $c->stash->{object},
		login => $login,
		css=>'topic_mainpage.css',
		template => 'topic/topic_mainpage.tt2');
}

sub comment:Chained('base') :PathPart('comment') :Args(0){
        my ( $self, $c ) = @_;
	#-100 is the pre-defined anonymous user
	my $comment_user_id = -100;
        if ($c->user_exists) {
                #$comment_user_id = $c->user->get('id');
                $comment_user_id = $c->session->{login_user}->id;
        }
        my $comment = $c->request->params->{comment}  || '';
        my $comm_id= $c->request->params->{comm_id} || '';
        my $topic_id= $c->request->params->{topic_id} || '';
	my $topic = $c->model('Topic::TopicSearchModel')->find($topic_id);
	#$topic->update({"lupd_user_id" => 0});
	$topic->update({"lupd_user_id" => $comment_user_id});
        $c->model('CommentedItem::CommentedItemModel')->add_to_comments($comm_id, $comment_user_id, $comment);

        $c->stash(comments => $c->model('Comments::CommentsForTopicModel')->get_comments($comm_id),
                nowrapper=> 1,
                javascript => '/topic/topic_all.js',
                template => 'topic/new_comment.tt2');
}


=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
